package com.jianguozh.difs.support.service.org;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jianguozh.difs.common.constant.ApiErrorCode;
import com.jianguozh.difs.common.exception.DifsException;
import com.jianguozh.difs.framework.utils.SpringUtils;
import com.jianguozh.difs.support.service.constant.enums.OrgEnum;
import com.jianguozh.difs.support.service.org.entity.Org;

import java.util.List;
import java.util.Map;

/**
 * 组织服务工厂
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/3/31 14:20
 */
public class OrgServiceFactory {

    private OrgEnum orgEnum;

    public OrgServiceFactory() {
    }

    public OrgServiceFactory(OrgEnum orgEnum) {
        this.orgEnum = orgEnum;
    }

    /**
     * 未设置管理员姓名和手机的组织
     *
     * @param orgIdList
     * @return
     */
    public List listNoneManager(List<String> orgIdList) {
        LambdaQueryWrapper<Org> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Org::getId, orgIdList);
        lambdaQueryWrapper.and(wrapper -> {
            wrapper.isNull(Org::getManager).or().isNull(Org::getManagerMobile);
        });
        return getOrgService().list(lambdaQueryWrapper);
    }

    /**
     * id集合检索组织
     *
     * @param orgIdList
     * @return
     */
    public List list(List<String> orgIdList) {
        LambdaQueryWrapper<Org> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Org::getId, orgIdList);
        return getOrgService().list(lambdaQueryWrapper);
    }

    /**
     * 批量获取组织名称
     *
     * @param orgList
     * @return
     */
    public List listOrgName(List orgList) {
        return getOrgService().listOrgName(orgList);
    }

    /**
     * 获取目标service
     *
     * @return
     */
    private OrgService getOrgService() {
        Map<String, OrgService> map = SpringUtils.getApplicationContext().getBeansOfType(OrgService.class);
        for (OrgService orgService : map.values()) {
            if (orgService.support(this.orgEnum)) {
                return orgService;
            }
        }
        throw new DifsException(ApiErrorCode.INTERNAL_ERROR);
    }

}
